import os

if __name__ == '__main__':
    file_name = 'test.txt'

    f = file('ansys_file/%s' % file_name, 'rb')
    new_file = file('ansys_file/.%s.bak' % file_name, 'wb')
    for line in f.xreadlines():
        new_file.write(line.replace('456', '123'))

    f.close()
    new_file.close()

    if os.path.exists('ansys_file/old.txt'):
        os.remove('ansys_file/old.txt')
    os.rename('ansys_file/%s' % file_name, 'ansys_file/old.txt')
    os.rename('ansys_file/.%s.bak' % file_name, 'ansys_file/%s' % file_name)